/************************************************
 * Author       :   XXY
 * Blog         :   https://www.cnblogs.com/jzyl
 * Gitee        :   https://gitee.com/xiaobaichong
 * Email        :   1047185209@QQ.com
 * FileName     :   BuildAssetBundle.cs
 * CreateData   :   2023/5/15 23:13:04
 * UnityVersion :   2021.3.20f1c1
 * Description  :   打包AssetBundle
************************************************/

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;
using Main;
using System.Linq;
using Newtonsoft.Json;
using System.Text;
using Sirenix.OdinInspector;

/// <summary>
/// 打包打包AssetBundle
/// </summary>
public class BuildAssetBundle
{
    [Title("Head")]
    [LabelWidth(150), Multiline]
    public string _Description = "将AB包资源打包为Unity活跃平台上的资源\n项目名称和版本可在Unity打包设置进行更改";

    [Title("构建AB包")]
    [SerializeField, LabelText("构建完成后是否压缩为ZIP文件")]
    private bool IsZip = false;
    [SerializeField, LabelText("目标构建平台")]
    private BuildTarget buildTarget = EditorUserBuildSettings.activeBuildTarget;

    [SerializeField, FolderPath, ReadOnly, LabelText("路径")]
    private string path = Path.GetFullPath(PathConfig.BuildAssetBundlePath);
    [SerializeField, LabelText("项目名称"), ReadOnly]
    private string productName;
    [SerializeField, LabelText("版本"), ReadOnly]
    private string version;


    public BuildAssetBundle()
    {
        Refresh();
    }

    //[MenuItem("Tools/MyTool/导出AB")]
    [Button("构建")]
    private void Build()
    {
        string path = PathConfig.AbsolutePath + PathConfig.BuildAssetBundlePath;
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        DirectoryInfo info = new DirectoryInfo(path);
        path = info.FullName;
        // 构建AB包
        AssetBundleManifest manifest = BuildPipeline.BuildAssetBundles(path, BuildAssetBundleOptions.None, buildTarget);
        // 获取所有AB包
        List<string> assetBundles = manifest.GetAllAssetBundles().ToList();
        // 添加AB依赖关系包
        assetBundles.Add(info.Name);
        // 获取所有AB包路径
        List<string> files = assetBundles.Select(abName => $"{path}{abName}").ToList();
        //生成文件Json
        ABJson abJson = new ABJson();
        abJson.projectName = productName;
        abJson.version = version;
        abJson.buildPlatform = buildTarget.ToString();
        abJson.abTotal = files.Count;
        long abSize = 0;
        foreach (var file in files)
        {
            FileInfo fileInfo = new FileInfo(file);
            ABInfo ab = new ABInfo();
            ab.name = fileInfo.Name;
            ab.size = fileInfo.Length;
            ab.md5 = FileUtility.GetFileMd5(file);
            abSize += ab.size;
            abJson.abArray.Add(ab.name, ab);
        }
        abJson.abSize = abSize;
        string json = JsonConvert.SerializeObject(abJson, Formatting.Indented);
        string abJsonPath = path + "MD5.json";
        File.WriteAllText(abJsonPath, json, Encoding.UTF8);
        files.Add(abJsonPath);

        if (IsZip)
        {
            // 压缩ZIP
            FileUtility.ZipFiles(files.ToArray(), $"{path}{info.Name}.zip");
        }
        // 打开目录
        FileUtility.OpenExplorer(path);
    }
    [Button("清空目录")]
    private void ClearDir()
    {
        string path = PathConfig.AbsolutePath + PathConfig.BuildAssetBundlePath;
        if (Directory.Exists(path))
        {
            Directory.Delete(path, true);
        }
    }
    [Button("刷新")]
    private void Refresh()
    {
        productName = Application.productName;
        version = Application.version;
        buildTarget = EditorUserBuildSettings.activeBuildTarget;
    }
}
